package com.sunni.validator;

import com.sunni.entity.validator.Student;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("/val")
public class Validator {

    @GetMapping("/stu")
//                     @Valid 对哪个数据进行验证  BindingResult: 收集错误的集合
    public void valStu(@Valid Student student, BindingResult bindingResult){

//        打印接收的对象
        System.out.println(student);

//        判断BindingResult是否含有错误
        if (bindingResult.hasErrors()){

//            有的话，获取所有错误
            List<ObjectError> errorList = bindingResult.getAllErrors();
//            遍历错误
            for (ObjectError error : errorList) {
//              getCode：@NotNull、@NotEmpty、@Min----.getDefaultMessage()：你自己在验证时定义的message
                System.out.println(error.getCode()+": "+error.getDefaultMessage());
            }
        }
    }

}
